package com.weactivity.controller;

import com.weactivity.config.MyWebSocket;
import com.weactivity.dto.Result;
import com.weactivity.dto.ToEmail;
import com.weactivity.entity.Reminder;
import com.weactivity.service.RemindService;
import com.weactivity.utils.UserHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/api/remind")
public class RemindController {

    @Autowired
    private RemindService remindService;

    /**
     * 这个方法是干什么的呢？
     *
     *
     * @return
     */

    @PostMapping("/test")
    //@Scheduled(cron = "0 0/1 * * * ?")
    public Result remindUserByEmail(){


       //List<Reminder> reminders =  remindService.findUserRemind();

        ToEmail toEmail = new ToEmail();
        toEmail.setReceivers(new String[] {"1492918560@qq.com"});
        return remindService.commonEmail(toEmail);

    }

    //@PostMapping("/alert")
    @Scheduled(cron = "0 0/1 * * * ?")
    public void remindUserByAlter(){

        //获得日程提醒时间到了的用户id
        //根据系统当前时间去数据库里面查询需要弹窗的日程提醒对象
        List<Reminder> reminders = remindService.findNeedtoAlert();
        for (Reminder reminder:reminders) {
            String userId = String.valueOf(reminder.getUid());
            String message = "您的日程提醒：" + reminder.getContent();
            // 检查用户是否在线
            if (MyWebSocket.isUserOnline(userId)) {
                MyWebSocket.sendReminder(userId, message);
            }
        }

    }


    @PostMapping("/create")
    public Result createReminder(@RequestParam("aid") int id,
                                 @RequestParam("content") String content,
                                 @RequestParam("remind_time") String remind_time){

       int count =  remindService.insertReminder(id,content,remind_time);
       if (0 == count){
           return Result.fail("创建失败");
       }

        return Result.ok("创建成功");
    }

    @GetMapping("/show")
    public Result showReminder(){

      List<Reminder> reminders =  remindService.showAll();
      if (null == reminders){
          return Result.fail("查询失败");
      }
      return Result.ok(reminders);

    }


    @DeleteMapping("/delete/{id}")
    public Result deleteReminder(@PathVariable("id") int id){

        int count =  remindService.deleteByid(id);

        if (0 == count)
        {
            return Result.fail("删除失败");
        }
        return Result.ok("删除成功");
    }
}
